/**
 * @author Paulo Faria Reis
 * @created 15 Mar 2012
 *
 */
package networkoperations;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import controller.DataStore;

/**
 * @author Paulo Faria Reis
 */
public class Replier extends Thread{
   volatile private boolean dontStop = true;
   MulticastSocket controlSocket = null;
   DataStore dataStorage;
   String whatToFind;
   File sharedDir;
   /**
    * @param dataStor 
    * @param string 
    * 
    */
   public Replier(DataStore dataStor, String searchRequest) {
	dataStorage = dataStor;
	whatToFind = searchRequest;
   }

   /* (non-Javadoc)
    * @see java.lang.Thread#run()
    */
   @Override
   public void run() {
	try {
	   controlSocket = new MulticastSocket();
	}
	catch (IOException e) {
	   System.out.println("Failure opening socket!");
	}
	String[] wordsToFind = whatToFind.split(" ");

	while(dontStop || dataStorage.keepWorking()) {
	   File[] filesInDir = dataStorage.getSharedDir().listFiles();	// Gets a array of File.
	   // Only the shared dir will be considered, not the subdirs. To include them we need a recursive listing of files and exclude the chunks dir (incomplete files).
	   for(int i = 0; i < filesInDir.length; i++) {
		if(filesInDir[i].isFile()) {
		   for(int j = 2; j < wordsToFind.length; j++) {	// First word is SEARCH, second is the id.
			if(filesInDir[i].getName().contains(wordsToFind[j])) {
			   byte[] buf = new byte[1024]; 
			   buf = ("FOUND " + wordsToFind[1] + " " + dataStorage.getSHA256(filesInDir[i]) + " " + filesInDir[i].length() + " " + filesInDir[i].getName()).getBytes();
			   DatagramPacket answer = new DatagramPacket(buf, buf.length, dataStorage.getMcAddress(), dataStorage.getControlPort());
			   try {
				controlSocket.send(answer);
			   }
			   catch (IOException e) {
				System.out.println("Failure to send FOUND message!");
			   }
			}
		   }
		} 
	   }
	   // Look in the "sha" dir too. It has file with the original name and content is the HASH.
	   File chunksDir = new File(dataStorage.getSharedDir(), "sha");
	   File[] chunksInDir = chunksDir.listFiles();

		for(int i  = 0; i < chunksInDir.length; i++) {
		   if(filesInDir[i].isFile()) {
			for(int j = 2; j < wordsToFind.length; j++) {	// First word is SEARCH, second is the id.
			   if(filesInDir[i].getName().contains(wordsToFind[j])) {			   
				try {
				   byte[] buf = new byte[1024];
				   char[] shaBuf = new char[1024];
				   FileReader fileInput = new FileReader(filesInDir[i]);
				   fileInput.read(shaBuf, 0, 1024);	// Reads the content of file (max 1024 chars), this is a the hash of the complete file.
				   buf = ("FOUND " + wordsToFind[1] + " " + shaBuf.toString() + " " + filesInDir[i].length() + " " + filesInDir[i].getName()).getBytes();
				   DatagramPacket answer = new DatagramPacket(buf, buf.length, dataStorage.getMcAddress(), dataStorage.getControlPort());
				   controlSocket.send(answer);
				}
				catch (FileNotFoundException e) {
				   System.out.println("Can't ready file!");
				}
				catch (IOException e) {
				   System.out.println("Failure to send FOUND message!");

			   }
			}
		   }	
		}
	   }
	}
   }

   // Method to ask the thread to stop.
   public void stopWork() {
	dontStop = false;
   }
}
